﻿using System;
using System.IO;
using System.Linq;
using Atmk.WaterMeter.MIS.Common;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Controllers.Pay.Base;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Kernel;
using Atmk.WaterMeter.MIS.Swaggers;
using Atmk.WaterMeter.MIS.TimedTask;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using NLog;
using Swashbuckle.AspNetCore.Swagger;

namespace Atmk.WaterMeter.MIS
{
    public class Startup
    {
        private static readonly ILogger _Logger = LogManager.GetCurrentClassLogger();

        private readonly string _projectName;

        public Startup(IConfiguration configuration)
        {
            _projectName = GetType().Namespace;
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(
                options =>
                {
                    //添加支持xml的输入和输出
                    options.InputFormatters.Add(new XmlSerializerInputFormatter(options));
                    options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
                }
            );
            services.AddSwaggerGen(c =>
            {
                typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
                {
                    c.SwaggerDoc(version, new Info
                    {
                        Version = version,
                        Title = $"{_projectName} 接口文档"
                    });
                });
                //在项目属性中手工定义的输出文件
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath = Path.Combine(basePath, $"{_projectName}.xml");
                c.IncludeXmlComments(xmlPath);
                c.OperationFilter<AssignOperationVendorExtensions>();
                c.DocumentFilter<ApplyTagDescriptions>();
            });
            services.AddDbContext<Context>(options => options.UseMySQL(ContextBuilder.Connection()));
            //跨域
            services.AddCors(options =>
            {
                options.AddPolicy("any", builder =>
                {
                    builder.AllowAnyOrigin() //允许任何来源的主机访问
                        //builder.WithOrigins("http://localhost:8080") ////允许http://localhost:8080的主机访问
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials(); //指定处理cookie
                });
            });

            services.AddHostedService<SettlementService>();
            //services.AddHostedService<OpenValveService>();
            services.AddHostedService<StatisticsService>();
        }

        public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance();
            builder.RegisterType<TokenHelper>().AsSelf();
            builder.RegisterType<WxTokenHelper>().AsSelf();
            builder.RegisterType<LogFileParseHelper>().AsSelf().SingleInstance();
            IoCManager.Instance.Register(builder);
            _Logger.Info($"Autofac Registe全部完成。");
        }

        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            //app.UseCors(build => build.WithOrigins("https://water-meter-demo.aixiyou.com:3385").AllowAnyHeader());
            //app.UseOptions();
            app.UseSwagger();
            app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", ApiVersions.v1.ToString()); });
            //跨域
            app.UseCors("any");

            app.UseStaticFiles();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    "default",
                    "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}